package com.yan.furns.web.servlet;

import com.yan.furns.entity.Cart;
import com.yan.furns.entity.Member;
import com.yan.furns.entity.Order;
import com.yan.furns.entity.OrderItem;
import com.yan.furns.service.OrderService;
import com.yan.furns.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author Yzb
 * @version 1.0
 */
public class OrderServlet extends BasicServlet {
	private OrderService orderService = new OrderServiceImpl();

	protected void saveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();

		Member member = (Member) session.getAttribute("member");
		System.out.println("验证登录");

		if (member == null) {
			resp.sendRedirect(req.getContextPath() + "/views/member/login.jsp");
			return;
		}

		System.out.println("已登录");
		Cart cart = (Cart) session.getAttribute("cart");

		System.out.println("验证购物车是否为空");
		if (cart == null || cart.isEmpty()) {
			resp.sendRedirect(req.getContextPath());
			return;
		}

		System.out.println("非空");
		orderService.saveOrder(cart, member.getId());
		resp.sendRedirect(req.getContextPath() + "/orderServlet?action=getOrders");
	}

	protected void getOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		Member member = (Member) session.getAttribute("member");
		if (member == null) {
			resp.sendRedirect(req.getContextPath() + "/views/member/login.jsp");
			return;
		}

		List<Order> orderList = orderService.getOrderList(member.getId());
		req.setAttribute("orderList", orderList);
		req.getRequestDispatcher("/views/order/order.jsp").forward(req, resp);
	}

	protected void getOrderDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String orderId = req.getParameter("orderId");
//		System.out.println(orderId);
		List<OrderItem> orderItemList = orderService.getOrderItemList(orderId);
//		System.out.println("============== getOrderDetail ================");
		req.setAttribute("orderItemList", orderItemList);
		req.setAttribute("orderId", orderId);
		req.setAttribute("order", orderService.getOrderByOrderId(orderId));
		req.getRequestDispatcher("/views/order/order_detail.jsp").forward(req, resp);
	}
}
